import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Board extends JPanel implements ActionListener {

    // panel 的宽度
    private final int B_WIDTH = 300;
    // 高
    private final int B_HEIGHT = 300;
    // 点的大小
    private final int DOT_SIZE = 10;
    // 一共有多少个点
    private final int ALL_DOTS = 900;
    // 下一个苹果出现位置，随机数种子
    private final int RAND_POS = 29;
    // 苹果出现间隔
    private final int DELAY = 140;

    // 二维数组用于定位
    private final int x[] = new int[ALL_DOTS];
    private final int y[] = new int[ALL_DOTS];

    // 苹果的点位
    private int dots;
    private int apple_x;
    private int apple_y;

    // 方向
    private boolean leftDirection = false;
    private boolean rightDirection = true;
    private boolean upDirection = false;
    private boolean downDirection = false;
    private boolean inGame = true;

    // 定时器和图片资源
    private Timer timer;
    private Image ball;
    private Image apple;
    private Image head;

    private Image yb;

    private int i = 0;
    // 初始化构造函数
    public Board() {

        initBoard();
    }

    private void initBoard() {

        // 添加按钮监听
        addKeyListener(new TAdapter());
        // 设置背景色
        setBackground(Color.black);
        // 设置当前 jpanel 获取焦点
        setFocusable(true);

        // 设置大小
        setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
        // 加载图片字眼
        loadImages();
        // 初始化游戏
        initGame();
    }

    private void loadImages() {
        // 实用 ImageIcon 类加载较为简单的图片资源
        ImageIcon iid = new ImageIcon("src/resource/dot.png");
        ball = iid.getImage();

        ImageIcon iia = new ImageIcon("src/resource/apple.png");
        apple = iia.getImage();

        ImageIcon iih = new ImageIcon("src/resource/head.png");
        head = iih.getImage();

        ImageIcon iiy = new ImageIcon("src/resource/yb.gif");
        yb = iiy.getImage();
    }

    //游戏初始化，设置游戏初始数据
    private void initGame() {
        // 蛇初始长度
        dots = 30;

        // 初始位置
        for (int z = 0; z < dots; z++) {
            x[z] = 50 - z * 10;
            y[z] = 50;
        }

        // 定位 苹果
        locateApple();

        // 设置定时器
        timer = new Timer(DELAY, this);
        // 启动定时器
        timer.start();
    }

    // 绘制组件
    // 复写父类 JPanel 中的绘制方法，加入自定义的绘制逻辑
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        doDrawing(g);
    }

    private void doDrawing(Graphics g) {
        /*
        if(i%2 == 0){
            setBackground(Color.black);
        }
        else {
            setBackground(Color.red);
        }
        i++;
        */
        // 如果游戏没结束，进入逻辑
        if (inGame) {

            // 通过 Jpanel 的 Grapics 对象 g 来进行自定义的2d图形绘制

            // 先画出苹果
            g.drawImage(apple, apple_x, apple_y, this);
            g.drawImage(yb,100,100,this);

            // 画蛇
            for (int z = 0; z < dots; z++) {
                if (z == 0) {
                    g.drawImage(head, x[z], y[z], this);
                } else {
                    g.drawImage(ball, x[z], y[z], this);
                }
            }

            // 同步刷新
            Toolkit.getDefaultToolkit().sync();

        } else {
            // 执行游戏结束逻辑
            gameOver(g);
        }
    }

    private void gameOver(Graphics g) {

        // 绘制一个游戏结束的文字
        String msg = "游戏结束！！！";

        // 字体类 Font 用来绘制蚊子
        Font small = new Font("Helvetica", Font.BOLD, 14);
        FontMetrics metr = getFontMetrics(small);
        // 设置字体颜色
        g.setColor(Color.white);
        // 应用字体
        g.setFont(small);
        // 绘制字体
        g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2);
    }

    // 看苹果有没有被吃
    private void checkApple() {
        // 如果苹果和蛇头位置重叠，说明苹果被吃
        if ((x[0] == apple_x) && (y[0] == apple_y)) {
            // 蛇身增长
            dots++;
            // 苹果消失
            locateApple();
        }
    }

    // 移动蛇
    private void move() {

        for (int z = dots; z > 0; z--) {
            x[z] = x[(z - 1)];
            y[z] = y[(z - 1)];
        }

        // 根据不同方向键来进行蛇的设定
        if (leftDirection) {
            x[0] -= DOT_SIZE;
        }

        if (rightDirection) {
            x[0] += DOT_SIZE;
        }

        if (upDirection) {
            y[0] -= DOT_SIZE;
        }

        if (downDirection) {
            y[0] += DOT_SIZE;
        }
    }

    // 看蛇有没有死
    private void checkCollision() {

        // 看蛇头有没有和边界以及蛇身相碰
        for (int z = dots; z > 0; z--) {

            if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
                inGame = false;
            }
        }

        if (y[0] >= B_HEIGHT) {
            inGame = false;
        }

        if (y[0] < 0) {
            inGame = false;
        }

        if (x[0] >= B_WIDTH) {
            inGame = false;
        }

        if (x[0] < 0) {
            inGame = false;
        }

        if (!inGame) {
            timer.stop();
        }
    }

    // 增加苹果
    private void locateApple() {

        int r = (int) (Math.random() * RAND_POS);
        apple_x = ((r * DOT_SIZE));

        r = (int) (Math.random() * RAND_POS);
        apple_y = ((r * DOT_SIZE));
    }

    // 设置刷新事件
    @Override
    public void actionPerformed(ActionEvent e) {

        if (inGame) {

            checkApple();
            checkCollision();
            move();
        }

        repaint();
    }

    // 进行键盘响应设置r
    private class TAdapter extends KeyAdapter {

        @Override
        public void keyPressed(KeyEvent e) {

            int key = e.getKeyCode();

            if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
                leftDirection = true;
                upDirection = false;
                downDirection = false;
            }

            if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
                rightDirection = true;
                upDirection = false;
                downDirection = false;
            }

            if ((key == KeyEvent.VK_UP) && (!downDirection)) {
                upDirection = true;
                rightDirection = false;
                leftDirection = false;
            }

            if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
                downDirection = true;
                rightDirection = false;
                leftDirection = false;
            }
        }
    }
}
